package com.bsj.pay.util.security;

import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import java.util.*;

public class DESUtil {
	private static final String IV_PARAMETER = "12345678";
	private static final String ALGORITHM = "DES";
	private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
	private static final String CHARSET = "utf-8";

	private static Key generateKey(final String password) throws Exception {
		final DESKeySpec dks = new DESKeySpec(password.getBytes("utf-8"));
		final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		return keyFactory.generateSecret(dks);
	}

	public static String encrypt(final String password, final String data) {
		if (password == null || password.length() < 8) {
			throw new RuntimeException("加密失败，key不能小于8位");
		}
		if (data == null) {
			return null;
		}
		try {
			final Key secretKey = generateKey(password);
			final Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			final IvParameterSpec iv = new IvParameterSpec("12345678".getBytes("utf-8"));
			cipher.init(1, secretKey, iv);
			final byte[] bytes = cipher.doFinal(data.getBytes("utf-8"));
			return new String(Base64.encode(bytes));
		} catch (Exception e) {
			e.printStackTrace();
			return data;
		}
	}

	public static String decrypt(final String password, final String data) {
		if (password == null || password.length() < 8) {
			throw new RuntimeException("加密失败，key不能小于8位");
		}
		if (data == null) {
			return null;
		}
		try {
			final Key secretKey = generateKey(password);
			final Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			final IvParameterSpec iv = new IvParameterSpec("12345678".getBytes("utf-8"));
			cipher.init(2, secretKey, iv);
			return new String(cipher.doFinal(Base64.decode(data)), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
			return data;
		}
	}
}
